package com.pangus.laizt.agedevhigh;

import java.io.IOException;
import java.util.Base64.Encoder;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;


public class TestAgeDevApi {

	private static final Logger logger = LoggerFactory.getLogger(TestAgeDevApi.class.getName());
	
	private static final String url = "http://10.21.2.200:28818/ims-mes";
	
	/**
	 *  检测sn
	 */
	@Test
	public void checkSn() {
		String postUrl = url+"/api/agedev/checkSn";
		JSONObject data = new JSONObject();
		data.put("sn", "WM081800008");
		String sendDataString = data.toJSONString();
		//账号名
		String userName = "streamax";
		//密码
		String passWord = "streamax";
		try {
			HttpRequest(postUrl, sendDataString,userName,passWord);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 上架绑定
	 */
	@Test
	public void bindSnAndStock() {
		String postUrl = url+"/api/agedev/saveSnAndStockCode";
		JSONObject data = new JSONObject();
		data.put("sn", "W210322S0004");
		data.put("stockCode", "001");
		String sendDataString = data.toJSONString();
		//账号名
		String userName = "streamax";
		//密码
		String passWord = "streamax";
		try {
			HttpRequest(postUrl, sendDataString,userName,passWord);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static String HttpRequest(String url, String sendDataString,String userName,String passWord) throws ClientProtocolException, IOException {
		Encoder encoder = java.util.Base64.getEncoder();
		String str = encoder.encodeToString((userName+":"+passWord).getBytes());
		HttpPost httppost = new HttpPost(url);
		if (sendDataString != null) {
			StringEntity stringEntity = new StringEntity(sendDataString, "UTF-8");
			stringEntity.setContentEncoding("UTF-8");
			httppost.setEntity(stringEntity);
		}
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();
		httppost.setConfig(requestConfig);
		httppost.setHeader("Content-Type", "application/json; charset=utf-8");
		httppost.setHeader("Accept", "application/json; charset=utf-8");
		httppost.setHeader("Authorization", str);
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = httpClient.execute(httppost);
		HttpEntity entity = response.getEntity();
		String result = EntityUtils.toString(entity);
		logger.info("结果"+result);
		return result;
	}
}
